package com.ItWaVel.filter;

import com.Emplyment.properties.JwtProperties;
import com.Emplyment.utils.jwtUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class ClientFilter implements Ordered, GlobalFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断是否是登录
        if (request.getURI().getPath().contains("/login") || request.getURI().getPath().contains("/register")) {
            //放行
            return chain.filter(exchange);
        }

        //在用户页面中、只有当用户去获取到preview以及面经时才会进行token验证
        if(request.getURI().getPath().contains("/preview")  || request.getURI().getPath().contains("/insertInterview")  || request.getURI().getPath().contains("/insertComment")
        || request.getURI().getPath().contains("/user")){
            log.info("用户页面请求校验");
            //3.获取token
            String token = request.getHeaders().getFirst("token");

            //4.判断token是否存在
            if (StringUtils.isBlank(token)) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //5.判断token是否有效
            try {
                log.info("token: " + token);
                Claims claims = jwtUtils.parseJWT(jwtProperties.getAdminSecretKey(), token);
                Long empId = Long.valueOf(claims.get("user_id").toString());
                log.info("员工id为:{}",empId);
                //通过，放行

                //存储header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("user_id", empId + "");
                }).build();

                return chain.filter(exchange.mutate().request(serverHttpRequest).build());
            }catch (Exception e) {
                //不通过，直接返回状态码401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
